package com.demo2do.fms.scheduler.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.http.annotation.Rao;
import com.demo2do.core.persistence.annotation.Dao;
import com.demo2do.fms.entity.business.Shipment;
import com.demo2do.fms.scheduler.dao.fms.FmsDao;
import com.demo2do.fms.scheduler.rao.ShipmentRao;
import com.demo2do.fms.scheduler.service.ShipmentWriter;

/**
 *
 * @author Ark
 *
 */
@Service("shipmentWriter")
public class ShipmentWriterImpl implements ShipmentWriter {
	
	private static final Logger logger = LoggerFactory.getLogger(ShipmentWriterImpl.class);
	
	@Value("#{config['shipment.electronic.url']}")
	private String electronicUrl;
    
    @Dao
    private FmsDao fmsDao;
    
    @Rao
    private ShipmentRao shipmentRao;

    /* (non-Javadoc)
     * @see com.demo2do.fms.scheduler.service.ShipmentWriter#sync(java.util.List)
     */
    public void sync(List<Shipment> shipments) {
    	
    	logger.warn("#sync() - sync shipment start...");
        
        // 1. prepare data
        List<Long> confirmShipments = new ArrayList<Long>();
        
        // 2. get unElectronicConfirm shipment
        for (Shipment shipment : shipments) {
            
            Map<String, Object> parameters = new HashMap<String, Object>();
            
            if (StringUtils.isBlank(shipment.getLoadNumber()) || shipment.getShipmentId() == null) {
            	continue;
            }

            // 2.1 get parameters
            parameters.put("loadNumber", shipment.getLoadNumber());
            parameters.put("shipmentId", shipment.getShipmentId());
            try{

                HttpResult httpResult = shipmentRao.searchElectronicConfirm(electronicUrl, parameters);

                // 2.2 if httpResult success, add will confirm
                if (httpResult.isValid()) {
                    confirmShipments.add(shipment.getId());
                }

            }catch (Exception e){

                logger.error("#sync() Exception [{}]","ERROR");
            }

            
        }
        
        // 3. update un electronic confirm shipment's electronic confirm
        if (CollectionUtils.isNotEmpty(confirmShipments)) {
        	fmsDao.syncShipment(confirmShipments);
        }
        
        logger.warn("#sync() - already sync shipment amount = [{}], shipment id = [{}]", confirmShipments.size(), StringUtils.join(confirmShipments, " , "));
        
    }

}
